package AdminDocker

import (
	"autoDeploy/config"
	"autoDeploy/dao/myselfMysql"
	"autoDeploy/models"
	"autoDeploy/utils/DingTalk"
	"autoDeploy/utils/Docker"
	"fmt"
	"strconv"
	"strings"
)

var db, _ = myselfMysql.CreateMySQLClient(config.MysqlDb)

// StringJoin 使用 strings.Builder 高效连接字符串
func StringJoin(container, captainId, teamId, path string) string {
	var sb strings.Builder
	sb.WriteString(container)
	sb.WriteRune('_')
	sb.WriteString(captainId)
	sb.WriteRune('_')
	sb.WriteString(teamId)
	sb.WriteRune('_')
	sb.WriteString(path)
	return sb.String()
}

//	GetDockerStatus
//
// 描述信息：查询用户的容器使用资源情况
//
// Param：
// Return：
//
//	[]Docker.ContainerStats ：容器情况结构体
//	error ：错误信息
func GetDockerStatus() ([]ProContainer, error) {
	var containerStats []ProContainer
	//查询全部的团队项目关联信息
	teamProjects, err := models.TeamProject{}.GetTeamProjects(db)
	if err != nil {
		return nil, fmt.Errorf("GetDockerStatus service层 GetTeamProjects err: %v", err)
	}
	//遍历数组中的数据
	length := len(teamProjects)
	for i := 0; i < length; i++ {
		team, err := models.Team{}.GetTeamByID(db, teamProjects[i].TeamID)
		if err != nil {
			return nil, fmt.Errorf("GetDockerStatus service层 GetTeamByID err: %v", err)
		}
		gitInfo, err := models.GetGitInfoByProjectID(db, teamProjects[i].ProjectID)
		if err != nil {
			return nil, fmt.Errorf("GetDockerStatus service层 GetGitInfoByProjectID err: %v", err)
		}
		//拼接docker容器名称
		containerName := StringJoin("container", strconv.FormatUint(team.CaptainUserID, 10), strconv.FormatUint(team.ID, 10), gitInfo.Path)
		stats, err := Docker.GetContainerStats(containerName)
		if err != nil {
			return nil, fmt.Errorf("GetDockerStatus service层 GetContainerStats err: %v", err)
		}
		containerStats = append(containerStats, ProContainer{
			BlockIO:     stats.BlockIO,
			CPUPerc:     stats.CPUPerc,
			Container:   stats.Container,
			ID:          stats.ID,
			MemPerc:     stats.MemPerc,
			MemUsage:    stats.MemUsage,
			Name:        stats.Name,
			NetIO:       stats.NetIO,
			PIDs:        stats.PIDs,
			TeamName:    team.Name,
			TeamAddress: team.Address,
		})
	}
	return containerStats, nil
}

// StopDocker 停止容器
func StopDocker(containerName string, address string) error {
	err := Docker.StopContainer(containerName)
	if err != nil {
		return fmt.Errorf("service stop container err: %v", err)
	}

	err = DingTalk.SendDockerStopMessageToDingTalk(address)
	if err != nil {
		return fmt.Errorf("service sendDingTalk docker stop err: %v", err)
	}
	return nil
}

// StartDocker 开始容器
func StartDocker(containerName string, address string) error {
	err := Docker.StartContainer(containerName)
	if err != nil {
		return fmt.Errorf("service start container err: %v", err)
	}
	err = DingTalk.SendDockerRunMessageToDingTalk(address)
	if err != nil {
		return fmt.Errorf("service sendDingTalk docker run err: %v", err)
	}
	return nil
}
